package com.ruoyi.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.domain.UserMessage;
import com.ruoyi.web.domain.dto.UserMessageDto;
import com.ruoyi.web.domain.vo.UserMessageVo;
import com.ruoyi.web.mapper.MonitorAreaMapper;
import com.ruoyi.web.mapper.UserMessageMapper;
import com.ruoyi.web.service.IUserMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements IUserMessageService {

    @Autowired
    private UserMessageMapper userMessageMapper;

    @Autowired
    private MonitorAreaMapper monitorAreaMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public AjaxResult leaveMsg(UserMessageDto dto) {
        UserMessage userMessage = new UserMessage();
        BeanUtils.copyProperties(dto, userMessage);
        if (StringUtils.equals("2", dto.getType()) && StringUtils.isNotBlank(dto.getUserName())) {
            SysUser sysUser = sysUserMapper.selectUserByUserName(dto.getUserName());
            if (sysUser == null) {
                return AjaxResult.error("留言失败，用户异常");
            }
            userMessage.setUserId(sysUser.getUserId());
        }
        userMessage.setCreateTime(LocalDateTime.now());
        if (StringUtils.equals("1", dto.getSource())) {
            userMessage.setSourceName("首页");
        } else if (StringUtils.equals("2", dto.getSource())) {
            String sourceName = monitorAreaMapper.getSourceNameByCameraId(dto.getCameraId());
            userMessage.setSourceName(sourceName);
        }
        userMessageMapper.insert(userMessage);
        return AjaxResult.success("留言成功");
    }

    @Override
    public List<UserMessageVo> getList(UserMessageDto dto) {
        return userMessageMapper.selectUserMessageList(dto);
    }

    @Override
    public AjaxResult delete(UserMessageDto dto) {
        userMessageMapper.deleteById(dto.getBaseId());
        return AjaxResult.success("删除成功");
    }

    @Override
    public Map<String, Integer> getUserMessageCount() {
        return userMessageMapper.selectUserMessageCount();
    }
}
